

package com.coding4play.mqtt.broker.protocol;

import com.coding4play.mqtt.common.entity.session.ChannelSession;
import com.coding4play.mqtt.common.repository.IDupPubRelMessageRepository;
import com.coding4play.mqtt.common.repository.IDupPublishMessageRepository;
import com.coding4play.mqtt.common.repository.ISessionRepository;
import com.coding4play.mqtt.common.repository.ISubMessageRepository;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.util.AttributeKey;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;


/**
 * DISCONNECT连接处理
 */
@AllArgsConstructor
@Slf4j
public class DisConnect {

    private ISessionRepository sessionRepository;
    private ISubMessageRepository subMessageRepository;
    private IDupPublishMessageRepository dupPublishMessageRepository;
    private IDupPubRelMessageRepository dupPubRelMessageRepository;

    public void processDisConnect(Channel channel, MqttMessage msg) {
        String clientId = (String) channel.attr(AttributeKey.valueOf("clientId")).get();
        ChannelSession channelSession = sessionRepository.get(clientId);
        if (channelSession != null && channelSession.getCleanSession()) {
            subMessageRepository.delete(clientId);
            dupPublishMessageRepository.delete(clientId);
            dupPubRelMessageRepository.delete(clientId);
        }
        log.debug("DISCONNECT - clientId: {}, cleanSession: {}", clientId, channelSession.getCleanSession());
        sessionRepository.delete(channelSession);
    }

}
